package com.yungam.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Configuration
public class HttpUtils {

    @Resource
    private RestTemplate restTemplate;

    /*
     * 发送 http 请求的工具方法
     * */
    public Map<String, Object> httpExchange(String url, HttpMethod httpMethod, Object data) {
        //
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json");
        headers.setContentType(type);
        headers.add("Company-Id", "13");

        //
        HttpEntity<String> entity;
        if (data == null) {
            entity = new HttpEntity<>(null, headers);
        } else if (data instanceof Map) {
            JSONObject json = new JSONObject((Map<String, Object>)data);
            entity = new HttpEntity<>(json.toString(), headers);
        } else {
            entity = new HttpEntity<>(JSON.toJSONString(data), headers);
        }

        try {
            ResponseEntity<JSONObject> res = restTemplate.exchange(url, httpMethod, entity, JSONObject.class);
            return res.getBody();
        } catch (Exception e) {
            log.error(url + "调用失败");
            e.printStackTrace();
            log.error(e.toString());
        }
        return null;
    }

}
